import datetime
import traceback

from sqlalchemy.orm import load_only

from applications.configs.func import get_password_hash
from applications.models import Session
from applications.models.novel import BookShelf
from applications.models.power import Power, UserPower
from applications.models.users import Users
from applications.schemas.Power import NowUserPowerList, PowerShowSchemas
from applications.schemas.Users import UserShow


# 递归获取权限
def get_power_list_recursion(result_list, power_list, parent_id=0, user_powers=[]):
    result = []
    for res in power_list:
        if res["parent_id"] == parent_id:
            res["checked"] = True if res["id"] in user_powers else False
            res["children"] = get_power_list_recursion(result_list, power_list, res["id"])
            result.append(res)
    return result


# 获取用户列表
def get_users_list():
    session = Session()
    try:
        # 获取数据
        user_list = session.query(Users).order_by(Users.id.asc()).all()
        return [UserShow.from_orm(i).dict() for i in user_list]
    except Exception:
        print("获取用户列表 异常", traceback.format_exc())
    finally:
        session.close()


# 获取权限列表
def get_power_list(user=None):
    session = Session()
    try:
        # 获取数据
        power_list = session.query(Power).order_by(Power.order.asc()).all()
        power_list = [PowerShowSchemas.from_orm(i).dict() for i in power_list]

        # 用户列表
        user_powers = []
        if user:
            user_power_list = session.query(UserPower).filter_by(user_id=user.id).all()
            user_powers = [u.power_id for u in user_power_list]
        # 增和数据结构
        return get_power_list_recursion({}, power_list, parent_id=0, user_powers=user_powers)
    except Exception:
        print("获取权限列表 异常", traceback.format_exc())
    finally:
        session.close()


# 获取当前用户菜单
def get_now_user_menus(user):
    if not user:
        return []

    session = Session()
    try:
        data = (session.query(UserPower.id, Power.remark, Power.name, Power.url).
                outerjoin(Power, UserPower.power_id == Power.id).
                filter(UserPower.user_id == user.id, Power.parent_id == 0).order_by(Power.order.asc()).
                all())
        return [NowUserPowerList.from_orm(i) for i in data]
    except Exception:
        print("获取权限列表 异常", traceback.format_exc())
    finally:
        session.close()


# 添加权限
def power_add_action(data):
    session = Session()
    try:
        # 查询是否存在
        if not session.query(Power).filter_by(url=data.url).first():
            power = Power(**data.dict(), enable=1, order=1)
            session.add(power)
            session.commit()

    except Exception as e:
        print("添加权限 异常", e)
        return False, e

    finally:
        session.close()
    return True, "操作成功"


# 修改用户信息
def user_update_update(data):
    session = Session()
    try:
        if data.id > 0:
            # 查询用户是否存在
            user = session.query(Users).filter_by(id=data.id).first()
            if not user:
                return False, "用户不存在"
            # 密码
            if data.password and len(data.password) > 1:
                user.password = get_password_hash(data.password)
            # 状态
            user.status = data.status
            user.last_use = datetime.datetime.now()

            session.query(UserPower).filter_by(user_id=data.id).delete()
        else:
            # 添加用户
            password = data.password
            user_session = Session()
            user = Users(password=password, username=data.username, status=data.status)
            user_session.add(user)
            user_session.commit()
            user_session.flush()
            user_session.close()

        # 权限
        for i in data.powers:
            session.add(UserPower(user_id=user.id, power_id=i))

        session.commit()

    except Exception:
        print("添加权限 异常", traceback.format_exc())
        session.rollback()
        return False, "操作失败"
    finally:
        session.close()

    return True, "操作成功"


# 删除用户
def user_delete_action(data):
    session = Session()
    try:
        if data.id > 0:
            # 查询用户是否存在
            user = session.query(Users).filter_by(id=data.id).first()
            if not user:
                return False, "用户不存在"

            # 删除用户书架
            session.query(BookShelf).filter_by(user_id=user.id).delete()
            # 删除用户权限
            session.query(UserPower).filter_by(user_id=user.id).delete()
            # 删除用户
            session.query(Users).filter_by(id=user.id).delete()

        session.commit()

    except Exception:
        print("删除用户 异常", traceback.format_exc())
        session.rollback()
        return False, "操作失败"
    finally:
        session.close()

    return True, "操作成功"


# 删除权限
def power_delete_action(data):
    session = Session()
    try:
        if data.id > 0:
            # 查询权限是否存在
            user = session.query(Power).filter_by(id=data.id).first()
            if not user:
                return False, "权限不存在"

            # 删除权限
            session.query(Power).filter_by(id=user.id).delete()
            # 删除用户权限
            session.query(UserPower).filter_by(power_id=user.id).delete()

        session.commit()

    except Exception:
        print("删除权限 异常", traceback.format_exc())
        session.rollback()
        return False, "操作失败"
    finally:
        session.close()

    return True, "操作成功"